﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Constant;
using BookShop.Site.Models;

namespace BookShop.Site.Controllers
{
    public class CartController : Controller
    {
        public ActionResult ShoppingCart()
        {
            var model = new OrderCartItemListModel { IsShoppingCartPage = true };
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart];
            model.CartItems = cartItemList;
            ViewBag.ShippingFee = ShoppingSurcharge.ShippingFee;
            return View(model);
        }

        public ActionResult CheckOut()
        {
            var model = new OrderCartItemListModel { IsShoppingCartPage = false };
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart];
            if (cartItemList == null || cartItemList.Count == 0)
            {
                return RedirectToAction("CheckOutResult", new { model = "Giỏ hàng rỗng!" });
            }
            model.CartItems = cartItemList;
            ViewBag.ShippingFee = ShoppingSurcharge.ShippingFee;
            return View(model);
        }

        [HttpPost]
        public ActionResult CheckOut(string fullName, string email, string phone, string primaryAddress,
            string secondaryAddress)
        {
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart];
            if (cartItemList == null || cartItemList.Count == 0)
            {
                return RedirectToAction("CheckOutResult", new { model = "Giỏ hàng rỗng!" });
            }
            var message = string.Empty;
            var order = new Order
            {
                CreateTime = DateTime.Now,
                ReceiverName = fullName,
                ReceiverPhone = phone.Trim(),
                Status = OrderStatus.New,
                PrimaryShippingAddress = primaryAddress.Trim(),
                SecondaryShippingAddress = secondaryAddress.Trim(),
                ReceiverEmail = email.Trim()
            };
            var customer = (Customer)Session[SessionKey.Customer];
            if (customer != null)
            {
                order.CustomerId = customer.Id;
                order.CustomerName = customer.FullName;
            }
            order.TotalPrice = cartItemList.Select(a => new { TotalPrice = a.Quantity * a.UnitPrice })
                .Sum(a => a.TotalPrice);
            order.TotalProductCount = cartItemList.Count;
            order = OrderService.Add(order);
            if (order != null)
            {
                foreach (var cartItem in cartItemList)
                {
                    if (cartItem.Book == null)
                    {
                        continue;
                    }
                    var orderDetail = new OrderDetail
                    {
                        BookId = cartItem.Book.Id,
                        OrderId = order.Id,
                        Quantity = cartItem.Quantity,
                        UnitPrice = cartItem.UnitPrice,
                        TotalPrice = cartItem.Quantity * cartItem.UnitPrice
                    };
                    var result = OrderDetailService.Add(orderDetail);
                    if (result == null)
                    {
                        message = AlertMessage.ErrorOccurs;
                        break;
                    }
                }
            }
            else
            {
                message = AlertMessage.ErrorOccurs;
            }
            Session.Remove(SessionKey.ShoppingCart);
            if (string.IsNullOrWhiteSpace(message))
            {
                ViewBag.Message = "Đặt hàng thành công! Cảm ơn bạn đã mua hàng tại Book Shop Ngân Hà!";
                return RedirectToAction("CheckOutResult");
            }
            return RedirectToAction("Error", "Home");
        }

        public void AddCartItem(int quantity, long bookId)
        {
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart] ?? new List<CartItem>();
            var book = BookService.GetById(bookId);
            if (book != null)
            {
                book = BookService.UpdateNotMappedField(book);
                var cartItem = cartItemList.FirstOrDefault(c => c.Book.Id == book.Id);
                if (cartItem == null)
                {
                    cartItem = new CartItem
                    {
                        Id = DateTime.Now.Ticks,
                        Book = book,
                        Quantity = quantity,
                        UnitPrice = book.IsOnSale ? book.DiscountPrice : book.Price
                    };
                    cartItemList.Add(cartItem);
                }
                else
                {
                    cartItem.Quantity += quantity;
                }
            }
            Session[SessionKey.ShoppingCart] = cartItemList;
        }

        public void DeleteCartItem(long cartItemId)
        {
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart] ?? new List<CartItem>();
            var cartItem = cartItemList.FirstOrDefault(c => c.Id == cartItemId);
            if (cartItem != null)
            {
                var isRemoved = cartItemList.Remove(cartItem);
                if (isRemoved)
                {
                    Session[SessionKey.ShoppingCart] = cartItemList;
                }
            }
        }

        public void EditCartItem(long cartItemId, int quantity)
        {
            var cartItemList = (List<CartItem>)Session[SessionKey.ShoppingCart] ?? new List<CartItem>();
            var cartItem = cartItemList.FirstOrDefault(c => c.Id == cartItemId);
            if (cartItem != null)
            {
                cartItem.Quantity = quantity;
                Session[SessionKey.ShoppingCart] = cartItemList;
            }
        }

        public ActionResult CheckOutResult()
        {
            return View();
        }
    }
}
